require("dotenv").config();
const mysql = require("mysql2/promise");
const logger = require("../utils/logger");

async function updateUserBalance() {
  let connection;

  try {
    // 创建数据库连接
    connection = await mysql.createConnection({
      socketPath: "/tmp/mysql.sock",
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
    });

    // 检查users表是否存在balance字段
    const [columns] = await connection.query(
      "SHOW COLUMNS FROM users LIKE 'balance'"
    );

    // 如果balance字段不存在，则添加
    if (columns.length === 0) {
      await connection.query(
        "ALTER TABLE users ADD COLUMN balance DECIMAL(18, 8) DEFAULT 0"
      );
      logger.info("成功为users表添加balance字段");
      console.log("成功为users表添加balance字段");
    } else {
      logger.info("users表已存在balance字段");
      console.log("users表已存在balance字段");
    }

    logger.info("数据库更新完成");
    console.log("数据库更新完成");
  } catch (error) {
    logger.error(`更新数据库时出错: ${error.message}`, { error: error.stack });
    console.error("更新数据库时出错:", error);
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

// 执行更新
updateUserBalance();
